Imports System.Data.SqlClient
Imports DevExpress.XtraEditors
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid

'--- Created By : Priyabrata
'--- Created On : 04-Oct-2010

Public Class frmChargeAndPayment
    Public blnAdd As Boolean, blnEdit As Boolean, blnDelete As Boolean
    Dim blnUnload As Boolean
    Dim mblnChanged As Boolean
    Dim mblnActivate As Boolean

    Dim mblnCancelDisplay As Boolean
    'Dim mUserStatusLVId As Integer
    Dim mPatientId As Integer
    Dim mVisitId As Integer
    Dim mPracticeId As Integer
    Dim dtCharge As New DataTable("Charges")
    Dim dtPayment As New DataTable("Payment")
    Public mblnFrmOutside As Boolean

    Public Sub New(ByVal IdVisit As Integer, ByVal IdPatient As Integer, ByVal IdPractice As Integer)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        mPatientId = IdPatient
        mVisitId = IdVisit
        mPracticeId = IdPractice
    End Sub

    Private Sub frmChargeAndPayment_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Try
            If mblnActivate = True Then
                mblnActivate = False
                pbRecords.Position = 20
                Application.DoEvents()
                'Populate Procedure

                '' ''Call PopulateLookupDX(lkProcedure, "ProcedureName", "ProcedureId", "tblProcedures", "ProcedureId,ProcedureName,Cost", "", "ProcedureName", , , 200)
                Call PopulateGridLookupDX(lkProcedure, "ProcedureName", "ProcedureId", "tblProcedures", "ProcedureId,ProcedureName,Cost", "", "ProcedureName", , , 400)
                lkProcedure.Properties.View.Columns("Cost").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                lkProcedure.Properties.View.Columns("Cost").DisplayFormat.FormatString = "0.00"
                ' '' ''Populate Item
                Call PopulateGridLookupDX(lkItem, "ItemName", "ItemId", "tblItem", "ItemId,ItemCode,ItemName,(Case When IsBillable=0 then 'No' When IsBillable=1 then 'Yes' End) [Billable],(Case When IsBillable=0 then 0 When IsBillable=1 then ChargeToPatient End)  [Charge],QOH", , "ItemName", , , 500)
                'Populate insuranceCompany 
                Call PopulateLookupDX(lkInsuranceCompany, "Insurance Company", "InsuranceCompanyId", "LtblInsuranceCompany", "InsuranceCompanyId,InsuranceCompany [Insurance Company]", , "InsuranceCompany")
                'Populate Paymenttype
                Call PopulateLookupDX(lkPaymentType, "Payment Type", "PaymentTypeId", "LtblPaymentType", "PaymentTypeId,PaymentType [Payment Type]", , "PaymentType")
                'Populate Bank Name
                Call PopulateLookupDX(cboBankName, "Bank Name", "BankId", "LtblBankName", "BankId,BankName [Bank Name]", , "BankName", True)
                Call EnableDisableControls(True)
                grbCheckCredit.Enabled = False

                pbRecords.Position = 40
                Application.DoEvents()

                Call btnCancelCharges_Click(Nothing, Nothing)
                Call btnCancelPayment_Click(Nothing, Nothing)

                Call CalculateTotal()
                pbRecords.Position = 80
                Application.DoEvents()

                Call DisplayCharges(0)
                Call DisplayPayment(0)
                Call chkNextAppointment_CheckedChanged(Nothing, Nothing)

                Dim dsTemp As DataSet = FillDataSet("SELECT NextAppointmentDate FROM tblVisits WHERE VisitId = " & mVisitId)
                If IsDBNullOrNothing(dsTemp.Tables(0).Rows(0).Item("NextAppointmentDate")) Then
                    dtNextAppointment.EditValue = Nothing
                    tmNextAppointment.EditValue = Nothing
                    If gintUserLevelId = 3 Or gintUserLevelId = 4 Then
                        lblNextAppointment.Visible = False
                        dtNextAppointment.Visible = False
                        tmNextAppointment.Visible = False
                    End If
                Else
                    dtNextAppointment.EditValue = Format(dsTemp.Tables(0).Rows(0).Item("NextAppointmentDate"), gstrDtFormat)
                    tmNextAppointment.EditValue = Format(dsTemp.Tables(0).Rows(0).Item("NextAppointmentDate"), "hh:mm tt")
                End If
                If mblnFrmOutside = True Then
                    grbPayment.Enabled = True
                    btnEnterPayment.Enabled = False
                    gintPaymentUserID = gintUserID
                Else
                    grbPayment.Enabled = False
                    btnEnterPayment.Enabled = True
                    gintPaymentUserID = Nothing
                End If
                pbRecords.Visible = True
                pbRecords.BringToFront()
                Application.DoEvents()
                pbRecords.Position = 100
                pbRecords.Visible = False
                lkProcedure.Focus()
                mblnChanged = False
                If gdvCharges.RowCount <= 0 Then
                    btnUpdateCharges.Enabled = False
                    btnUpdateItems.Enabled = False
                    btnDeleteCharges.Enabled = False
                    btnDeleteItems.Enabled = False
                    btnAddCharges.Enabled = True
                    btnAddItems.Enabled = True
                    btnAddItems.Text = "&A"
                    btnAddCharges.Text = "&A"
                End If
            End If

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmChargeAndPayment_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        mblnCancelDisplay = True
        'If blnKeyTrap(e.KeyCode, Me, True, grdRecords) = True Then mblnCancelDisplay = False : Exit Sub
        mblnCancelDisplay = False

        pbRecords.Visible = False
    End Sub

    Private Sub frmChargeAndPayment_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim rowCount As Int16 = 0
        Try

            Application.DoEvents()
            Call SetImageControl(Me)

            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgFormIcons.Images(2), Bitmap).GetHicon())
            Call GetAccessPermission(Me, "frmChargeAndPayment")
            Call setPBRecords(Me, pbRecords)
            Call InitializedDataEntry()

            'if user is other than Admin then dont allow to delete as well as update charges and payments
            If gintUserLevelId <> 1 Then
                btnDeletePayment.Enabled = False
                btnUpdatePayment.Enabled = False
            End If

            'set next Appointment time
            chkNextAppointment.Checked = False

            If gintUserLevelId = 1 Or gintUserLevelId = 2 Then
                chkNextAppointment.Visible = True
            Else
                chkNextAppointment.Visible = False
                'dtpNextAppointment.Enabled = False
            End If
            
            mblnActivate = True
            mblnChanged = False

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub InitializedDataEntry()
        Dim fnBold As New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold)

        With dtCharge.Columns
            .Add("Date", GetType(Date))
            .Add("Procedure", GetType(String))
            .Add("Quantity", GetType(Integer))
            .Add("Cost", GetType(Decimal))
            .Add("Charge Amount", GetType(Decimal))
            .Add("ProcedureTypeId", GetType(Integer))
            .Add("ID", GetType(Integer))
            .Add("VisitId", GetType(Integer))
            .Add("Type", GetType(String))
        End With
        grdCharges.DataSource = dtCharge

        With gdvCharges
            .Columns("Date").AppearanceHeader.Font = fnBold
            .Columns("Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
            .Columns("Date").DisplayFormat.FormatString = gstrDtFormat & " hh:mm tt"
            .Columns("Procedure").AppearanceHeader.Font = fnBold
            .Columns("Quantity").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            .Columns("Quantity").AppearanceHeader.Font = fnBold
            .Columns("Quantity").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
            .Columns("Quantity").DisplayFormat.FormatString = "0"
            .Columns("Cost").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            .Columns("Cost").AppearanceHeader.Font = fnBold
            .Columns("Cost").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
            .Columns("Cost").DisplayFormat.FormatString = "0.00"
            .Columns("Cost").Caption = "Price"
            .Columns("Charge Amount").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            .Columns("Charge Amount").AppearanceHeader.Font = fnBold
            .Columns("Charge Amount").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
            .Columns("Charge Amount").DisplayFormat.FormatString = "0.00"
            .Columns("Charge Amount").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Sum, "{0:0.00}")
            .Columns("ProcedureTypeId").Visible = False
            .Columns("ProcedureTypeId").OptionsColumn.ShowInCustomizationForm = False
            .Columns("ID").Visible = False
            .Columns("ID").OptionsColumn.ShowInCustomizationForm = False
            .Columns("Type").Visible = False
            .Columns("Type").OptionsColumn.ShowInCustomizationForm = False
            .Columns("VisitId").Visible = False
            .Columns("VisitId").OptionsColumn.ShowInCustomizationForm = False
            .OptionsView.ColumnAutoWidth = True
            .OptionsBehavior.Editable = False
        End With

        With dtPayment.Columns
            .Add("Payment Type", GetType(String))
            .Add("Date", GetType(Date))
            .Add("Payment Amount", GetType(Decimal))

            .Add("Status", GetType(Integer))
            .Add("Number", GetType(String))
            .Add("Bank Name", GetType(String))
            .Add("Check Date", GetType(Date))
            .Add("Drawer", GetType(String))
            .Add("Visit Date", GetType(Date))

            .Add("PaymentId", GetType(Integer))
            .Add("VisitId", GetType(Integer))
            .Add("PatientId", GetType(Integer))
            .Add("TypePaymentId", GetType(Integer))
            .Add("InsuranceCompanyId", GetType(Integer))
            .Add("CheckId", GetType(Integer))
        End With
        grdPayment.DataSource = dtPayment

        With gdvPayment
            .Columns("Payment Type").AppearanceHeader.Font = fnBold
            .Columns("Date").AppearanceHeader.Font = fnBold
            .Columns("Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
            .Columns("Date").DisplayFormat.FormatString = gstrDtFormat
            .Columns("Payment Amount").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            .Columns("Payment Amount").AppearanceHeader.Font = fnBold
            .Columns("Payment Amount").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom
            .Columns("Payment Amount").DisplayFormat.FormatString = "0.00"
            .Columns("Payment Amount").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Sum, "{0:0.00}")

            .Columns("Status").Visible = False
            .Columns("Status").OptionsColumn.ShowInCustomizationForm = False
            .Columns("Number").Visible = False
            .Columns("Number").OptionsColumn.ShowInCustomizationForm = False
            .Columns("Bank Name").Visible = False
            .Columns("Bank Name").OptionsColumn.ShowInCustomizationForm = False
            .Columns("Check Date").Visible = False
            .Columns("Check Date").OptionsColumn.ShowInCustomizationForm = False
            .Columns("Drawer").Visible = False
            .Columns("Drawer").OptionsColumn.ShowInCustomizationForm = False
            .Columns("VisitId").Visible = False
            .Columns("VisitId").OptionsColumn.ShowInCustomizationForm = False
            .Columns("Visit Date").Visible = False
            .Columns("Visit Date").OptionsColumn.ShowInCustomizationForm = False

            .Columns("PaymentId").Visible = False
            .Columns("PaymentId").OptionsColumn.ShowInCustomizationForm = False
            .Columns("PatientId").Visible = False
            .Columns("PatientId").OptionsColumn.ShowInCustomizationForm = False
            .Columns("TypePaymentId").Visible = False
            .Columns("TypePaymentId").OptionsColumn.ShowInCustomizationForm = False
            .Columns("InsuranceCompanyId").Visible = False
            .Columns("InsuranceCompanyId").OptionsColumn.ShowInCustomizationForm = False
            .Columns("CheckId").Visible = False
            .Columns("CheckId").OptionsColumn.ShowInCustomizationForm = False

            .OptionsView.ColumnAutoWidth = True
            .OptionsBehavior.Editable = False
        End With
    End Sub

    Private Sub PopulateChargesInGrid()
        Dim DoctorCriteria As String
        If gintUserLevelId = 1 OrElse gintUserLevelId = 2 Then
            DoctorCriteria = " AND tblVisits.PracticeId=" & GetPracticeId(gintUserID) & " "
        Else
            DoctorCriteria = ""
        End If

        Dim strQuery As String = "SELECT VisitDate[Date],ProcedureName[Procedure],Quantity" & _
                                ",tblCharges.Cost AS Cost ,Quantity * tblCharges.Cost  [Charge Amount],ProcedureTypeId,ChargeId [ID],tblVisits.VisitId,[Type]='Charges'" & _
                                " FROM tblCharges JOIN  tblProcedures ON tblCharges.ProcedureTypeId=tblProcedures.ProcedureId" & _
                                " JOIN  tblVisits ON tblVisits.VisitId=tblCharges.VisitId" & _
                                " WHERE tblVisits.VisitId = " & mVisitId & DoctorCriteria & _
                                " Union All " & _
                                "SELECT VisitDate [Date],ItemName[Procedure],Quantity," & _
                                "IsNull(ChargeToPatient,0) AS Cost,Quantity * Isnull(ChargeToPatient,0)  [Charge Amount],tblInventoryIssue.ItemId [ProcedureTypeId],IssueId [ID],tblInventoryIssue.VisitId,[Type]='Inventory'" & _
                                " FROM tblInventoryIssue JOIN tblItem ON tblInventoryIssue.ItemId=tblItem.ItemId" & _
                                " JOIN  tblVisits ON tblVisits.VisitId=tblInventoryIssue.VisitId" & _
                                " WHERE tblVisits.VisitId = " & mVisitId & DoctorCriteria
        Dim dsTemp As DataSet = FillDataSet(strQuery)

        With grdCharges
            .BeginUpdate()
            .DataSource = dsTemp.Tables(0)
            .EndUpdate()
        End With
    End Sub

    Private Sub PopulatePaymentInGrid()
        Dim DoctorCriteria As String
        If gintUserLevelId = 1 OrElse gintUserLevelId = 2 Then
            DoctorCriteria = " AND tblVisits.PracticeId=" & GetPracticeId(gintUserID) & " "
        Else
            DoctorCriteria = ""
        End If

        'Call PopulateComboDX(cboBankName, "tblCheck", "Distinct BankName")

        Dim strQuery As String = "SELECT DISTINCT PaymentType[Payment Type],PaymentDate[Date],CAST(Payment AS DEC(8,2)) [Payment Amount]," & _
                                "tblPayment.PaymentId, tblPayment.PatientId," & _
                                "tblPayment.PaymentTypeId as TypePaymentId,InsuranceCompanyId,tblPayment.CheckId as CheckId," & _
                                "Status,Number,BankName [Bank Name],CheckDate [Check Date],Drawer FROM " & _
                                "(tblPayment JOIN LtblPaymentType ON tblPayment.PaymentTypeId=LtblPaymentType.PaymentTypeId)  " & _
                                "JOIN tblVisits ON tblVisits.PatientId=tblPayment.PatientId LEFT OUTER JOIN tblCheck ON " & _
                                "tblPayment.CheckId=tblCheck.CheckId  WHERE tblPayment.PatientId = " & mPatientId & _
                                " AND (DATEDIFF(dd, GetDate(), tblPayment.PaymentDate) = 0)"

        Dim dsTemp As DataSet = FillDataSet(strQuery)
        With grdPayment
            .BeginUpdate()
            .DataSource = dsTemp.Tables(0)
            .EndUpdate()
        End With
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub grdCharges_EmbeddedNavigator_ButtonClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.NavigatorButtonClickEventArgs) Handles grdCharges.EmbeddedNavigator.ButtonClick
        ''Delete the row and update the row in database
        'If e.Button.ButtonType = NavigatorButtonType.Remove Then
        '    If MessageBox.Show("Do you want to delete this charge?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then
        '        e.Handled = False
        '    Else
        '        e.Handled = True
        '    End If
        'End If
    End Sub

    Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDeletePayment.Click
        Try
            mblnChanged = False
            If MessageBox.Show("Do you want to delete this payment?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then
                Exit Sub
            Else
                Call DeleteFromTable("tblPayment", "PaymentId=" & gdvPayment.GetRowCellValue(gdvPayment.FocusedRowHandle, "PaymentId"))
                Call PopulatePaymentInGrid()
                Call CalculateTotal()
                'grbPayment.Enabled = False
                'btnEnterPayment.Enabled = True
                'gdvPayment.DeleteRow(gdvPayment.FocusedRowHandle)
                'grdPayment.EmbeddedNavigator.Buttons.DoClick(grdPayment.EmbeddedNavigator.Buttons.Remove)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub lkPaymentType_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkPaymentType.EditValueChanged
        mblnChanged = True
        Try
            If IsDBNullOrNothing(lkPaymentType.EditValue) = False Then
                grbCheckCredit.Enabled = False
                txtNumber.Text = ""
                cboBankName.EditValue = Nothing
                dteCheckDate.EditValue = Now.ToShortDateString()
                txtDrawer.Text = ""

                If lkPaymentType.EditValue = 4 Or lkPaymentType.EditValue = 8 Then
                    grbCheckCredit.Enabled = True
                    grbCheckCredit.Text = "For Check Payment"
                    lblNumber.Text = "Check Number"
                    lblCheckDate.Text = "Check Date"

                    lblBankName.Text = "Bank Name"
                    lblDrawer.Text = "Drawer"

                End If
                If lkPaymentType.EditValue = 8 Then
                    grbCheckCredit.Enabled = True
                    grbCheckCredit.Text = "For Credit Card"
                    lblNumber.Text = "Card Number"
                    lblCheckDate.Text = "Expiry Date"

                    lblBankName.Text = "Bank Name"
                    lblBankName.Text = "Bank Name"
                    lblDrawer.Text = "Card Holder"
                End If
                If lkPaymentType.EditValue = 5 Then
                    'Insurance Company
                    lkInsuranceCompany.Enabled = True
                    lblInsuranceCompany.Enabled = True
                Else
                    lkInsuranceCompany.Enabled = False
                    lblInsuranceCompany.Enabled = False
                End If

            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnAddNewPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddNewPayment.Click
        Try
            If btnAddNewPayment.Text = "&New" Then
                btnAddNewPayment.Text = "&Add"
                lkPaymentType.EditValue = DBNull.Value
                txtPayment.EditValue = "0.00"
                lkInsuranceCompany.EditValue = DBNull.Value
                txtNumber.Text = ""
                cboBankName.EditValue = Nothing
                dteCheckDate.EditValue = Now.ToShortDateString()
                txtDrawer.Text = ""
                btnUpdatePayment.Enabled = False
                btnDeletePayment.Enabled = False
                grbCheckCredit.Enabled = False
                lkInsuranceCompany.Enabled = False
                lkPaymentType.Focus()
            Else

                If IsPaymentBoxValid() = False Then    'check if user has entered values in textbox
                    Exit Sub
                End If

                LoadCursor(Me)

                Dim CheckId As Integer
                Dim strQurey As String

                If lkPaymentType.EditValue = 4 OrElse lkPaymentType.EditValue = 8 Then
                    InsertUpdateCheckData(CheckId, True)
                End If

                strQurey = mPatientId & ","
                strQurey = strQurey & lkPaymentType.EditValue & ","
                strQurey = strQurey & mPracticeId & ","
                strQurey = strQurey & "'" & Today.ToShortDateString & "',"
                strQurey = strQurey & Val(txtPayment.EditValue) & ","
                strQurey = strQurey & IIf(IsDBNullOrNothing(lkInsuranceCompany.EditValue) = True, "NULL", lkInsuranceCompany.EditValue) & ","
                strQurey = strQurey & CheckId & ","
                strQurey = strQurey & gintPaymentUserID
                Call InsertintoTable("tblPayment", strQurey)

                btnAddNewPayment.Text = "&New"

                Call PopulatePaymentInGrid()
                gdvPayment.MoveLast()
                mblnChanged = False
                Call CalculateTotal()
                'grbPayment.Enabled = False
                'btnEnterPayment.Enabled = True
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Call EnableDisableControls(True)
            DestroyCrushor(Me)
        End Try
    End Sub

    Private Function IsPaymentBoxValid() As Boolean

        If IsDBNullOrNothing(lkPaymentType.EditValue) = True Then
            MessageBox.Show("Please select Payment Type.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            lkPaymentType.Focus()
            Return False
        End If

        If txtPayment.EditValue <= 0 Then
            MessageBox.Show("Please enter Amount.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            txtPayment.Focus()
            Return False
        End If

        If Not IsNumeric(txtPayment.EditValue) Then
            MessageBox.Show("Please enter Amount in number.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            txtPayment.Focus()
            txtPayment.SelectAll()
            Return False
        End If

        If lkPaymentType.EditValue = 4 OrElse lkPaymentType.EditValue = 8 Then ' 4=Check, 8=card
            If Trim(txtNumber.Text) = "" Then
                MessageBox.Show("Please enter " & IIf(lkPaymentType.EditValue = 4, "Check #", "Card #"), gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                txtNumber.Focus()
                Return False
            End If
        End If

        If lkPaymentType.EditValue = 4 OrElse lkPaymentType.EditValue = 8 Then ' 4=Check, 8=card
            If IsDBNullOrNothing(cboBankName.EditValue) Then
                MessageBox.Show("Please select Bank Name.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                cboBankName.Focus()
                Return False
            End If
        End If

        If lkPaymentType.EditValue = 4 OrElse lkPaymentType.EditValue = 8 Then ' 4=Check, 8=card
            If IsDBNullOrNothing(dteCheckDate.EditValue) Then
                MessageBox.Show("Please enter " & IIf(lkPaymentType.EditValue = 4, "Check Date.", "Expiry Date."), gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                dteCheckDate.Focus()
                Return False
            End If
        End If

        If lkPaymentType.EditValue = 4 OrElse lkPaymentType.EditValue = 8 Then ' 4=Check, 8=card
            If Trim(txtDrawer.Text) = "" Then
                MessageBox.Show("Please enter " & IIf(lkPaymentType.EditValue = 4, "Drawer's", "Card holder's") & " Name.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                txtDrawer.Focus()
                Return False
            End If
        End If
        Return True
    End Function

    'this function inserts check data and sets CheckId to newly inserted CheckId.Returns true if successful
    Private Sub InsertUpdateCheckData(ByRef CheckId As Integer, ByVal IsInsertQuery As Boolean)
        Dim strQuery As String

        Try
            If IsInsertQuery OrElse CheckId = 0 Then
                'Insert data for check or credit card.
                strQuery = IIf(lkPaymentType.EditValue = 4, 1, "NULL") & ","
                strQuery = strQuery & SmartReplace(txtNumber.EditValue) & ","
                strQuery = strQuery & SmartReplace(cboBankName.EditValue) & ","
                strQuery = strQuery & "'" & dteCheckDate.EditValue & "',"
                strQuery = strQuery & txtPayment.EditValue & ","
                strQuery = strQuery & SmartReplace(txtDrawer.EditValue)
                Call InsertintoTable("tblCheck", strQuery, "Status, Number, BankName, CheckDate, Amount,Drawer")
                'get CheckId which is used to insert data into tblPayment
                CheckId = GetId("tblCheck")
            Else
                'Update Check data
                strQuery = " Status=" & IIf(lkPaymentType.EditValue = 4, 1, "NULL") & ","
                strQuery = strQuery & " Number=" & SmartReplace(txtNumber.EditValue) & ","
                strQuery = strQuery & " BankName=" & SmartReplace(cboBankName.EditValue) & ","
                strQuery = strQuery & " CheckDate=" & "'" & dteCheckDate.EditValue & "',"
                strQuery = strQuery & " Amount=" & txtPayment.EditValue & ","
                strQuery = strQuery & " Drawer=" & SmartReplace(txtDrawer.EditValue)
                Call UpdateTable("tblCheck", strQuery, " CheckId=" & CheckId)

            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub EnableDisableControls(ByVal blnEnable As Boolean)
        If blnAdd = True Then
            btnAddNewPayment.Enabled = blnEnable
            'btnAddCharges.Enabled = blnEnable
            'btnAddItems.Enabled = blnEnable
        Else
            btnAddNewPayment.Enabled = False
            'btnAddCharges.Enabled = False
            'btnAddItems.Enabled = False
        End If
        If blnEdit = True Then
            btnUpdatePayment.Enabled = blnEnable
            'btnUpdateCharges.Enabled = blnEnable
            'btnUpdateItems.Enabled = blnEnable
        Else
            btnUpdatePayment.Enabled = False
            'btnUpdateCharges.Enabled = False
            'btnUpdateItems.Enabled = False
        End If
        If blnDelete = True Then
            btnDeletePayment.Enabled = blnEnable
            'btnDeleteCharges.Enabled = blnEnable
            'btnDeleteItems.Enabled = blnEnable
        Else
            btnDeletePayment.Enabled = False
            'btnDeleteCharges.Enabled = False
            'btnDeleteItems.Enabled = False
        End If
        'If gdvCharges.RowCount = 0 Then
        '    btnUpdateCharges.Enabled = False : btnDeleteCharges.Enabled = False
        '    btnUpdateItems.Enabled = False : btnDeleteItems.Enabled = False
        'End If
        If gdvPayment.RowCount = 0 Then
            btnUpdatePayment.Enabled = False : btnDeletePayment.Enabled = False

        End If

    End Sub

    'Private Sub AddRowInPaymentGrid(ByVal dtTemp As DataTable)
    '    Dim drRow As DataRow = dtTemp.NewRow()
    '    drRow("Payment Type") = Trim(lkPaymentType.Text)
    '    drRow("Date") = txtPayment.EditValue
    '    drRow("Payment Amount") = txtPayment.EditValue

    '    drRow("Number") = Trim(txtNumber.Text)
    '    drRow("Bank Name") = Trim(txtNumber.Text)
    '    drRow("Check Date") = Trim(txtNumber.Text)
    '    drRow("Drawer") = Trim(txtNumber.Text)

    '    drRow("PatientId") = mPatientId
    '    drRow("TypePaymentId") = lkPaymentType.EditValue
    '    drRow("InsuranceCompanyId") = lkInsuranceCompany.EditValue

    'End Sub

    Private Sub btnAddCharges_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddCharges.Click
        Try
            If btnAddCharges.Text = "&N" Then
                btnAddCharges.Text = "&A"
                lkProcedure.EditValue = DBNull.Value
                txtQuantity.EditValue = "1"
                txtCharge.Text = ""
                btnUpdateCharges.Enabled = False
                btnDeleteCharges.Enabled = False
                lkProcedure.Focus()
            Else
                If IsChargeBoxValid() = False Then    'check if user has entered values in textbox
                    Exit Sub
                End If

                LoadCursor(Me)
                Dim strQuery As String
                strQuery = mVisitId & "," & lkProcedure.EditValue & "," & txtQuantity.EditValue & "," & Val(txtCharge.EditValue)

                Call InsertintoTable("tblCharges", strQuery, "VisitId,ProcedureTypeId,Quantity,Cost")
                Call PopulateChargesInGrid()
                gdvCharges.MoveLast()
                Call CalculateTotal()
                mblnChanged = False
                btnAddCharges.Text = "&N"
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Call EnableDisableControls(True)
            DestroyCrushor(Me)
        End Try
    End Sub

    Private Function IsChargeBoxValid() As Boolean
        If IsDBNullOrNothing(lkProcedure.EditValue) = True Then
            MessageBox.Show("Please select Procedure.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            lkProcedure.Focus()
            Return False
        End If
        If Not IsDBNullOrNothing(txtCharge.Text) Then
            If Val(txtCharge.EditValue) <= 0 Then
                MessageBox.Show("Please enter proper charge.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                txtCharge.Focus()
                Return False
            End If
            If Not IsNumeric(txtCharge.EditValue) Then
                MessageBox.Show("Please enter charge in number.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                txtQuantity.Focus()
                txtQuantity.SelectAll()
                Return False
            End If
        Else
            MessageBox.Show("Please enter proper charge.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            txtCharge.Focus()
            Return False
        End If
        
        If Not IsDBNullOrNothing(txtQuantity.Text) Then
            If Val(txtQuantity.EditValue) <= 0 Then
                MessageBox.Show("Please enter Quantity.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                txtQuantity.Focus()
                Return False
            End If

            If Not IsNumeric(txtQuantity.EditValue) Then
                MessageBox.Show("Please enter Quantity in number.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                txtQuantity.Focus()
                txtQuantity.SelectAll()
                Return False
            End If
        Else
            MessageBox.Show("Please enter Quantity.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            txtQuantity.Focus()
            Return False
        End If
        

        Return True
    End Function


    Private Function IsInventoryBoxValid() As Boolean
        If IsDBNullOrNothing(lkItem.EditValue) = True Then
            MessageBox.Show("Please select Item.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            lkItem.Focus()
            Return False
        End If

        If txtItemQuantity.EditValue <= 0 Then
            MessageBox.Show("Please enter Quantity.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            txtItemQuantity.Focus()
            Return False
        End If

        If Not IsNumeric(txtItemQuantity.EditValue) Then
            MessageBox.Show("Please enter Quantity in number.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
            txtItemQuantity.Focus()
            txtItemQuantity.SelectAll()
            Return False
        End If

        Return True
    End Function

    Private Sub btnDeleteCharges_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteCharges.Click
        Try
            mblnChanged = False
            If gdvCharges.GetRowCellValue(gdvCharges.FocusedRowHandle, "Type") = "Charges" Then
                If MessageBox.Show("Do you want to delete this charges?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then
                    Exit Sub
                Else
                    Call DeleteFromTable("tblCharges", "ChargeId=" & gdvCharges.GetRowCellValue(gdvCharges.FocusedRowHandle, "ID"))
                    Call PopulateChargesInGrid()
                    Call CalculateTotal()
                    btnCancelCharges_Click(Nothing, Nothing)
                    'gdvCharges.DeleteRow(gdvCharges.FocusedRowHandle)
                    'grdCharges.EmbeddedNavigator.Buttons.DoClick(grdCharges.EmbeddedNavigator.Buttons.Remove)
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnUpdatePayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdatePayment.Click
        Try
            Dim strQuery As String
            If IsPaymentBoxValid() = False Then    'check if user has entered values in textbox
                Exit Sub
            End If
            Dim CheckId As Integer
            CheckId = gdvPayment.GetRowCellValue(gdvPayment.FocusedRowHandle, "CheckId")
            If lkPaymentType.EditValue = 4 OrElse lkPaymentType.EditValue = 8 Then
                InsertUpdateCheckData(CheckId, False)
            Else
                DeleteFromTable("tblCheck", " CheckId=" & CheckId)
            End If

            strQuery = " PatientId = " & mPatientId & ", "
            strQuery = strQuery & " PracticeId = " & mPracticeId & ","
            strQuery = strQuery & " PaymentTypeId= " & lkPaymentType.EditValue & ","
            strQuery = strQuery & " PaymentDate='" & Today.ToShortDateString & "',"
            strQuery = strQuery & " Payment= " & txtPayment.EditValue & ","
            strQuery = strQuery & " InsuranceCompanyId= " & IIf(IsDBNullOrNothing(lkInsuranceCompany.EditValue) = True, "NULL", lkInsuranceCompany.EditValue) & ","
            strQuery = strQuery & " CheckId= " & CheckId & ","
            strQuery = strQuery & " UserId= " & gintPaymentUserID
            Call UpdateTable("tblPayment", strQuery, "PaymentId=" & gdvPayment.GetRowCellValue(gdvPayment.FocusedRowHandle, "PaymentId"))
            Dim intHandel As Integer = gdvPayment.FocusedRowHandle
            Call PopulatePaymentInGrid()
            gdvPayment.FocusedRowHandle = intHandel
            Call CalculateTotal()
            mblnChanged = False
            'grbPayment.Enabled = False
            'btnEnterPayment.Enabled = True
            ' MessageBox.Show("Payment updated.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Call EnableDisableControls(True)
            DestroyCrushor(Me)
        End Try
    End Sub

    Private Sub btnUpdateCharges_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdateCharges.Click
        Try
            Dim strQuery As String
            If IsChargeBoxValid() = False Then    'check if user has entered values in textbox
                Exit Sub
            End If
            strQuery = "ProcedureTypeId=" & lkProcedure.EditValue & ",Quantity=" & txtQuantity.EditValue
            strQuery = strQuery & ",VisitId=" & gdvCharges.GetRowCellValue(gdvCharges.FocusedRowHandle, "VisitId")
            strQuery = strQuery & ",Cost=" & gdvCharges.GetRowCellValue(gdvCharges.FocusedRowHandle, "Cost")
            Call UpdateTable("tblCharges", strQuery, "ChargeId=" & gdvCharges.GetRowCellValue(gdvCharges.FocusedRowHandle, "ID"))
            Dim intHandel As Integer = gdvCharges.FocusedRowHandle
            Call PopulateChargesInGrid()
            gdvCharges.FocusedRowHandle = intHandel
            Call CalculateTotal()
            mblnChanged = False
            'MessageBox.Show("Charges updated.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Call EnableDisableControls(True)
            DestroyCrushor(Me)
        End Try
    End Sub

    Private Sub grdPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles grdPayment.Click
        Try
            Call DisplayPayment(gdvPayment.FocusedRowHandle)
            lkPaymentType.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Call EnableDisableControls(True)
        End Try
    End Sub

    Private Sub DisplayPayment(ByVal intRowhandel As Integer)
        Dim dr As DataRow = dtPayment.NewRow()
        dr = gdvPayment.GetDataRow(intRowhandel)
        If IsDBNullOrNothing(dr) = False Then
            lkPaymentType.EditValue = dr.Item("TypePaymentId")
            txtPayment.EditValue = dr.Item("Payment Amount")
            lkInsuranceCompany.EditValue = dr.Item("InsuranceCompanyId")
            txtNumber.Text = dr.Item("Number") & ""
            If IsDBNullOrNothing(dr.Item("Bank Name")) Then
                cboBankName.EditValue = Nothing
            Else
                cboBankName.EditValue = CInt(Val(dr.Item("Bank Name")))
            End If

            dteCheckDate.EditValue = dr.Item("Check Date") & ""
            txtDrawer.Text = dr.Item("Drawer") & ""
        End If
        mblnChanged = False
    End Sub

    Private Sub grdCharges_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles grdCharges.Click
        Try
            Call DisplayCharges(gdvCharges.FocusedRowHandle)
            'lkProcedure.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Call EnableDisableControls(True)
        End Try
    End Sub

    Private Sub DisplayCharges(ByVal intRowhandel As Integer)
        Dim dr As DataRow = dtCharge.NewRow()
        dr = gdvCharges.GetDataRow(intRowhandel)
        If IsDBNullOrNothing(dr) = False Then
            If dr.Item("Type") = "Charges" Then
                lkProcedure.EditValue = dr.Item("ProcedureTypeId")
                txtQuantity.EditValue = dr.Item("Quantity")
                txtCharge.EditValue = dr.Item("Cost")
                lkItem.EditValue = Nothing
                txtItemQuantity.EditValue = Nothing
                txtItemCharge.EditValue = Nothing
                lkProcedure.Focus()
            ElseIf dr.Item("Type") = "Inventory" Then
                lkItem.EditValue = dr.Item("ProcedureTypeId")
                txtItemQuantity.EditValue = dr.Item("Quantity")
                txtItemCharge.EditValue = dr.Item("Cost")
                lkProcedure.EditValue = Nothing
                txtQuantity.EditValue = Nothing
                txtCharge.EditValue = Nothing
                lkItem.Focus()
            End If
            
        End If
        mblnChanged = False
    End Sub

    Private Sub btnCancelPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelPayment.Click
        Call PopulatePaymentInGrid()
        mblnChanged = False
        If gdvPayment.RowCount > 0 Then
            btnAddNewPayment.Text = "&New"
            Call EnableDisableControls(True)
            Call DisplayPayment(0)
        Else
            lkPaymentType.EditValue = DBNull.Value
            txtPayment.EditValue = "0.00"
            lkInsuranceCompany.EditValue = DBNull.Value
            txtNumber.Text = ""
            cboBankName.EditValue = Nothing
            dteCheckDate.EditValue = Now.ToShortDateString()
            txtDrawer.Text = ""
            btnUpdatePayment.Enabled = False
            btnDeletePayment.Enabled = False
            grbCheckCredit.Enabled = False
            btnAddNewPayment.Text = "&Add"
            lkPaymentType.Focus()
        End If
        'grbPayment.Enabled = False
        'btnEnterPayment.Enabled = True
    End Sub

    Private Sub btnCancelCharges_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelCharges.Click
        Call PopulateChargesInGrid()
        mblnChanged = False
        If gdvCharges.RowCount > 0 Then
            btnAddCharges.Text = "&N"
            Call EnableDisableControls(True)
            Call DisplayCharges(0)
        Else
            lkProcedure.EditValue = Nothing
            txtQuantity.EditValue = Nothing
            txtCharge.Text = ""
            btnAddCharges.Text = "&A"
            lkProcedure.Focus()
        End If
    End Sub

    Private Sub frmChargeAndPayment_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        Try
            If chkNextAppointment.Checked = True AndAlso IsDBNullOrNothing(dtNextAppointment.EditValue) = False AndAlso IsDBNullOrNothing(tmNextAppointment.EditValue) = False Then
                Call UpdateTable("tblVisits", "NextAppointmentDate ='" & Format(dtNextAppointment.EditValue, gstrDtFormat) & " " & Format(tmNextAppointment.EditValue, "hh:mm tt") & "'", "VisitId=" & mVisitId)
            Else
                Call UpdateTable("tblVisits", "NextAppointmentDate = NULL", "VisitId=" & mVisitId)
            End If

            'Ask user to save changes.
            'If ((btnAddCharges.Text = "&A" And btnAddItems.Text = "&A") Or btnAddNewPayment.Text = "&New") And ((btnUpdateCharges.Enabled = True And btnUpdateItems.Enabled = True) Or btnUpdatePayment.Enabled = True) Then

            If mblnChanged = True Then
                If MessageBox.Show("Do you want to save changes?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
                    'save changes in Charges
                    If btnAddCharges.Text = "&A" And btnUpdateCharges.Enabled = True And Val(lkProcedure.EditValue) > 0 Then
                        Call btnUpdateCharges_Click(sender, e)
                    ElseIf btnAddCharges.Text = "&A" And btnUpdateCharges.Enabled = False And Val(lkProcedure.EditValue) > 0 Then
                        Call btnAddCharges_Click(sender, e)
                    End If
                    If btnAddItems.Text = "&A" And btnUpdateItems.Enabled = True And Val(lkItem.EditValue) > 0 Then
                        Call btnUpdateItems_Click(sender, e)
                    ElseIf btnAddItems.Text = "&A" And btnUpdateItems.Enabled = False And Val(lkItem.EditValue) > 0 Then
                        Call btnAddItems_Click(sender, e)
                    End If
                    'save changes in Payment
                    If btnAddNewPayment.Text = "&Add" And btnUpdatePayment.Enabled = True Then
                        Call btnUpdatePayment_Click(sender, e)
                    End If

                End If
            End If



            'End If
            gintPaymentUserID = Nothing
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmChargeAndPayment_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        Try
            Dim TotalPayment As Decimal = Val(gdvPayment.Columns("Payment Amount").SummaryText & "")
            If TotalPayment > 0 Then
                ChangeStatus(mVisitId, PatientStatus.VisitComplete)
                gblnIsRefreshed = True
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub chkNextAppointment_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkNextAppointment.CheckedChanged
        dtNextAppointment.Enabled = chkNextAppointment.Checked
        tmNextAppointment.Enabled = chkNextAppointment.Checked
    End Sub

    Private Sub gdvCharges_RowCountChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvCharges.RowCountChanged
       
    End Sub

    Private Sub gdvPayment_FocusedRowChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gdvPayment.FocusedRowChanged
        Try
            Call DisplayPayment(gdvPayment.FocusedRowHandle)
            lkPaymentType.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Call EnableDisableControls(True)
        End Try
    End Sub

    Private Sub gdvPayment_RowCountChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvPayment.RowCountChanged
        If gdvPayment.RowCount > 0 Then
            btnAddNewPayment.Text = "&New"
            Call EnableDisableControls(True)
        Else
            btnAddNewPayment.Text = "&Add"
            btnUpdatePayment.Enabled = False
            btnDeletePayment.Enabled = False
        End If
    End Sub

    Private Sub CalculateTotal()
        'fill total balance text
        Dim TotalBalance As Double
        TotalBalance = Val(gdvCharges.Columns("Charge Amount").SummaryText & "") - Val(gdvPayment.Columns("Payment Amount").SummaryText & "")
        txtTodayBalance.EditValue = TotalBalance
        'In Old software this has done.
        'TotalBalance = Val(strRecordID("tblCharges INNER JOIN tblVisits ON tblCharges.VisitId = tblVisits.VisitId INNER JOIN tblPatientInfo ON tblVisits.PatientId = tblPatientInfo.PatientId INNER JOIN tblPayment ON tblPatientInfo.PatientId = tblPayment.PatientId INNER JOIN tblProcedures ON tblCharges.ProcedureTypeId = tblProcedures.ProcedureId", "SUM(tblCharges.Quantity * tblProcedures.Cost) - SUM(tblPayment.Payment) AS TotalBalance ", " tblPatientInfo.PatientId=" & mPatientId & " GROUP BY tblPayment.Payment ") & "")
        TotalBalance = (Val(strRecordID("tblCharges Join tblVisits On (tblCharges.VisitId=tblVisits.VisitId)" & _
                                       " Join tblProcedures On (tblCharges.ProcedureTypeId=tblProcedures.ProcedureId)", _
                                       "Sum((tblCharges.Quantity*tblCharges.Cost))", "tblVisits.PatientID=" & mPatientId)) _
                                       + Val(strRecordID("tblInventoryIssue Join tblVisits On tblInventoryIssue.VisitId=tblVisits.VisitId " & _
                                        " Join tblItem on tblInventoryIssue.ItemId=tblItem.ItemId", _
                                        "Sum((tblInventoryIssue.Quantity*IsNull(tblItem.ChargeToPatient,0)))", "tblVisits.PatientID=" & mPatientId))) _
                     - Val(strRecordID("tblPayment", "Sum(tblPayment.Payment)", "tblPayment.PatientID=" & mPatientId))
        txtTotalBalance.EditValue = TotalBalance
    End Sub

    Private Sub gdvCharges_FocusedRowChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gdvCharges.FocusedRowChanged
        Try
            Call DisplayCharges(gdvCharges.FocusedRowHandle)
            'lkProcedure.Focus()
            If gdvCharges.RowCount > 0 Then
                If gdvCharges.GetRowCellValue(gdvCharges.FocusedRowHandle, "Type") = "Charges" Then
                    'dr.Item("Type") = "Charges"
                    btnAddCharges.Text = "&N"
                    btnUpdateCharges.Enabled = True
                    btnDeleteCharges.Enabled = True
                    btnUpdateItems.Enabled = False
                    btnDeleteItems.Enabled = False
                ElseIf gdvCharges.GetRowCellValue(gdvCharges.FocusedRowHandle, "Type") = "Inventory" Then
                    btnAddItems.Text = "&N"
                    btnUpdateItems.Enabled = True
                    btnDeleteItems.Enabled = True
                    btnUpdateCharges.Enabled = False
                    btnDeleteCharges.Enabled = False
                End If
                Call EnableDisableControls(True)
            Else
                btnAddCharges.Text = "&A"
                btnAddItems.Text = "&A"
                btnUpdateCharges.Enabled = False
                btnDeleteCharges.Enabled = False
                btnUpdateItems.Enabled = False
                btnDeleteItems.Enabled = False
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Call EnableDisableControls(True)
        End Try
    End Sub

    Private Sub btnEnterPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnterPayment.Click
        Dim frmTempChargesLogin As New frmChargesPaymentLogin
        With frmTempChargesLogin
            '.MdiParent = Me.ParentForm
            .ShowInTaskbar = False
            .ShowDialog()
            .Dispose()
            GC.Collect()
        End With
        If gintPaymentUserID > 0 Then
            btnEnterPayment.Enabled = False
            grbPayment.Enabled = True
            lkPaymentType.Focus()
        Else
            btnEnterPayment.Enabled = True
            grbPayment.Enabled = False
        End If
    End Sub

    Private Sub btnAddItems_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddItems.Click
        Try
            If btnAddItems.Text = "&N" Then
                btnAddItems.Text = "&A"
                lkItem.EditValue = DBNull.Value
                txtItemQuantity.EditValue = "1"
                txtItemCharge.Text = ""
                btnUpdateItems.Enabled = False
                btnDeleteItems.Enabled = False
                lkItem.Focus()
            Else
                If IsInventoryBoxValid() = False Then    'check if user has entered values in textbox
                    Exit Sub
                End If

                LoadCursor(Me)
                Dim strQuery As String
                strQuery = lngAutogeneratePrimaryKey("tblInventoryIssue", "IssueId") & _
                            " , " & mVisitId & _
                            " , " & lkItem.EditValue & _
                            " , " & txtItemQuantity.EditValue & _
                            " , 0" & _
                            " , " & SmartReplace(gstrUserName & "-" & Format(gdtCurrentDate, "dd-MMM-yyyy hh:mm:ss tt"))
                Call InsertintoTable("tblInventoryIssue", strQuery)
                Dim Qoh As Integer = Val(strRecordID("tblItem", "QOH", "ItemId=" & Val(lkItem.EditValue)))
                If Qoh < 0 Then
                    MessageBox.Show("After this transaction the stock of " & lkItem.Text & " will be negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                End If
                Call PopulateChargesInGrid()
                gdvCharges.MoveLast()
                Call CalculateTotal()
                mblnChanged = False
                btnAddItems.Text = "&N"
            End If
        Catch ex As Exception
            If ex.Message.Contains("Negative") Then
                MessageBox.Show("After this transaction Stock will be Negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Else
                MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                    Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
            End If
            
        Finally
            Call EnableDisableControls(True)
            DestroyCrushor(Me)
        End Try
    End Sub

    Private Sub btnUpdateItems_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdateItems.Click
        Try
            Dim strQuery As String
            If IsInventoryBoxValid() = False Then    'check if user has entered values in textbox
                Exit Sub
            End If
            strQuery = "ItemId=" & lkItem.EditValue & _
                        ",Quantity=" & txtItemQuantity.EditValue & _
                        ",LastModified=" & SmartReplace(gstrUserName & "-" & Format(gdtCurrentDate, "dd-MMM-yyyy hh:mm:ss tt"))
            Call UpdateTable("tblInventoryIssue", strQuery, "IssueId=" & gdvCharges.GetRowCellValue(gdvCharges.FocusedRowHandle, "ID"))
            Dim intHandel As Integer = gdvCharges.FocusedRowHandle
            Dim Qoh As Integer = Val(strRecordID("tblItem", "QOH", "ItemId=" & Val(lkItem.EditValue)))
            If Qoh < 0 Then
                MessageBox.Show("After this transaction the stock of " & lkItem.Text & " will be negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
            Call PopulateChargesInGrid()
            
            gdvCharges.FocusedRowHandle = intHandel
            Call CalculateTotal()
            mblnChanged = False
            'MessageBox.Show("Charges updated.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch ex As Exception
            If ex.Message.Contains("Negative") Then
                MessageBox.Show("After this transaction Stock will be Negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Else
                MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                    Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
            End If
        Finally
            Call EnableDisableControls(True)
            DestroyCrushor(Me)
        End Try
    End Sub

    Private Sub btnDeleteItems_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteItems.Click
        Try
            mblnChanged = False
            If MessageBox.Show("Do you want to delete this charges?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then
                Exit Sub
            Else
                Call DeleteFromTable("tblInventoryIssue", "IssueId=" & gdvCharges.GetRowCellValue(gdvCharges.FocusedRowHandle, "ID"))
                Dim Qoh As Integer = Val(strRecordID("tblItem", "QOH", "ItemId=" & Val(lkItem.EditValue)))
                If Qoh < 0 Then
                    MessageBox.Show("After this transaction the stock of " & lkItem.Text & " will be negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                End If
                Call PopulateChargesInGrid()
                Call CalculateTotal()

                Call btnCancelItems_Click(Nothing, Nothing)
                'gdvCharges.DeleteRow(gdvCharges.FocusedRowHandle)
                'grdCharges.EmbeddedNavigator.Buttons.DoClick(grdCharges.EmbeddedNavigator.Buttons.Remove)
            End If
        Catch ex As Exception
            If ex.Message.Contains("Negative") Then
                MessageBox.Show("After this transaction Stock will be Negative.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Else
                MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
                AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                    Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
            End If
        End Try
    End Sub

    Private Sub btnCancelItems_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelItems.Click
        Call PopulateChargesInGrid()
        mblnChanged = False
        If gdvCharges.RowCount > 0 Then
            btnAddItems.Text = "&N"
            Call EnableDisableControls(True)
            Call DisplayCharges(0)
        Else
            lkItem.EditValue = DBNull.Value
            txtItemQuantity.EditValue = Nothing
            txtItemCharge.Text = ""
            btnAddItems.Text = "&A"
            lkItem.Focus()
        End If
    End Sub
    Private Sub lkProcedure_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkProcedure.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateGridLookupDX(lkProcedure, "ProcedureName", "ProcedureId", "tblProcedures", "ProcedureId,ProcedureName,Cost", "", "ProcedureName", , , 400)
            lkProcedure.Properties.View.Columns("Cost").DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
            lkProcedure.Properties.View.Columns("Cost").DisplayFormat.FormatString = "0.00"
        End If
    End Sub

    Private Sub lkItem_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkItem.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateGridLookupDX(lkItem, "ItemName", "ItemId", "tblItem", "ItemId,ItemCode,ItemName,(Case When IsBillable=0 then 'No' When IsBillable=1 then 'Yes' End) [Billable],(Case When IsBillable=0 then 0 When IsBillable=1 then ChargeToPatient End)  [Charge],QOH", , "ItemName", , , 500)
        End If
    End Sub

    Private Sub lkItem_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkItem.EditValueChanged
        mblnChanged = True
       
    End Sub

    Private Sub lkProcedure_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkProcedure.EditValueChanged
        mblnChanged = True
       
    End Sub

    Private Sub btnAddCharges_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles btnAddCharges.MouseMove
        If btnAddCharges.Text = "&A" Then
            btnAddCharges.ToolTip = "Add"
        ElseIf btnAddCharges.Text = "&N" Then
            btnAddCharges.ToolTip = "New"
        End If
    End Sub

    Private Sub btnAddItems_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles btnAddItems.MouseMove
        If btnAddItems.Text = "&A" Then
            btnAddItems.ToolTip = "Add"
        ElseIf btnAddItems.Text = "&N" Then
            btnAddItems.ToolTip = "New"
        End If
    End Sub

    Private Sub cboBankName_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles cboBankName.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookupDX(cboBankName, "Bank Name", "BankId", "LtblBankName", "BankId,BankName [Bank Name]", , "BankName", True)
        End If
    End Sub

    Private Sub cboBankName_ProcessNewValue(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles cboBankName.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            cboBankName.EditValue = Nothing
            cboBankName.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblBankName"
            .mintGrbId = 1
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(cboBankName, "Bank Name", "BankId", "LtblBankName", "BankId,BankName [Bank Name]", , "BankName", True)
            If mlngLookUpId > 0 Then
                cboBankName.EditValue = CInt(mlngLookUpId)
            Else
                cboBankName.EditValue = Nothing
                cboBankName.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub txtCharge_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCharge.TextChanged
        mblnChanged = True
    End Sub

    Private Sub txtQuantity_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtQuantity.TextChanged
        mblnChanged = True
    End Sub

    Private Sub txtItemCharge_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtItemCharge.TextChanged
        mblnChanged = True
    End Sub

    Private Sub txtItemQuantity_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtItemQuantity.TextChanged
        mblnChanged = True
    End Sub

    Private Sub txtPayment_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPayment.TextChanged, txtNumber.TextChanged, txtDrawer.TextChanged
        mblnChanged = True
    End Sub

    Private Sub lkInsuranceCompany_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkInsuranceCompany.EditValueChanged, dteCheckDate.EditValueChanged, cboBankName.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub lkProcedure_ParseEditValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs) Handles lkProcedure.ParseEditValue
        If IsDBNullOrNothing(e.Value) Then Exit Sub
        Dim dr As DataRowView = CType(lkProcedure.Properties.GetRowByKeyValue(e.Value), DataRowView)
        'Dim ItemDetailsDataRow As DataRow
        'ItemDetailsDataRow = CType(lkProcedure.Properties.View.GetDataRow(lkProcedure.Properties.View.FocusedRowHandle), DataRow)
        'If IsDBNullOrNothing(ItemDetailsDataRow) Then Exit Sub
        If IsDBNullOrNothing(dr("Cost")) = False Then
            txtCharge.Text = Format(dr("Cost"), "0.00")
        Else
            txtCharge.Text = Nothing
        End If
        btnAddCharges.Text = "&A"
        txtQuantity.Text = "1"
    End Sub

    Private Sub lkItem_ParseEditValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs) Handles lkItem.ParseEditValue
        If IsDBNullOrNothing(e.Value) Then Exit Sub
        Dim dr As DataRowView = CType(lkItem.Properties.GetRowByKeyValue(e.Value), DataRowView)
        'Dim ItemDetailsDataRow As DataRow
        'ItemDetailsDataRow = CType(lkItem.Properties.View.GetDataRow(lkItem.Properties.View.FocusedRowHandle), DataRow)
        'If IsDBNullOrNothing(ItemDetailsDataRow) Then Exit Sub
        If IsDBNullOrNothing(dr("Charge")) = False Then
            txtItemCharge.Text = dr("Charge")
        Else
            txtItemCharge.Text = Nothing
        End If
        btnAddItems.Text = "&A"
        txtItemQuantity.Text = "1"
    End Sub
End Class
